#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.userInfoController import UserInfoController
from app import db
from utils.response_code import RET, error_map_EN
from utils import commons
from models.userInfoModel import UserInfo


class UserInfoService(UserInfoController):
    # 用户登录
    @classmethod
    def login(cls, **kwargs):
        account = kwargs.get('account')
        password = kwargs.get('password')
        try:
            user_info = db.session.query(cls).filter(cls.account == account).first()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常,登录失败"}}

        # 验证用户是否存在
        if not user_info:
            return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'data': {'error': '用户不存在'}}

        user_info_data = commons.query_to_dict(user_info)
        # print(user_info_data)

        # 校验密码
        try:
            if password != user_info_data.get('password'):
                return {'code': RET.LOGINERR, 'message': error_map_EN[RET.LOGINERR], 'data': {'error': '密码错误'}}
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常，密码查验失败"}}

        result = {
            'username': user_info_data.get('username'),
            'account': user_info_data.get('account'),
            'userID': user_info_data.get('userID')
        }
        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': result}



        pass

    # 用户注册
    @classmethod
    def register(cls, **kwargs):
        # 先判断用户是不是存在
        try:
            user_info = db.session.query(cls).filter(cls.account == kwargs.get('account')).first()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': '数据库连接异常'}}

        # 如果用户已经存在
        if user_info:
            return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST], 'data': {'error': '该用户已经注册'}}

        # 生成用户逻辑主键userID
        try:
            from utils.generate_id import GenerateID
            userID = GenerateID.create_random_id()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': '数据库生成ID错误'}}

        # 注册
        try:
            user = UserInfo(
                userID=int(userID),
                username=kwargs.get('username'),
                account=kwargs.get('account'),
                password=kwargs.get('password')
            )
            db.session.add(user)
            db.session.commit()
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': error_map_EN[RET.OK]}
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': '数据库链接异常，无法添加记录'}}
        finally:
            db.session.close()



